package com.itboye.ihomebank.activity.qianyue;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.util.alipay.OrderInfoUtil2_0;
import com.itboye.ihomebank.util.alipay.PayResult;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.BindCardsList;
import com.itboye.ihomebank.bean.PayInfo;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.RongFengsBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.activity.me.ActivityZhangHu;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimeFormat;
import com.itboye.ihomebank.util.WritePassPopupWindow;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog.OnfinishListener;
import com.itboye.ihomebank.web.WebActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 支付
 */
public class PayActivity extends BaseOtherActivity implements Observer,
        OnfinishListener {
    View v_statusbar;
    TextView go_pay, add_shap_title_tv, heji, benqi;
    ImageView close_icon;
    String money, contracNo, pay_code_type;
    UserPresenter userPresenter;
    private String uid;
    ImageView zhifubao_selectBtn, wx_selectBtn, yue_selectBtn,
            yinhangka_selectBtn, xiaotong_selectBtn;
    boolean zfb = true, wx;
    private PayInfo payInfo;
    private String items;
    private boolean yhk;
    private boolean yue;
    private String bankId;
    RelativeLayout choose_card;

    TextView bank_type, card_type, item_zhanghu_num,txt_xiaotong;
    private WritePassPopupWindow passPopupWindow;
    EditText pass;
    private boolean xiaotong;
    private CharSequence fenQiCount = "";
    //平安支付
    private ImageView safety_selectBtn;
    private RelativeLayout choose_safetycard;
    private TextView bank_safetytype,card_safetytype,item_zhanghu_safetynum;
    private boolean safety;
    private long creatTime;//合同创建日期  小于2018.7.24 支持全部支付  大于2018.7.24 只支持余额支付 和平安银行支付

    private RelativeLayout seventh,inner,re_xiaotong;
    // /第三方支付方式，int,[0=>无第三方(todo),1=>支付宝，2=>微信(todo)，3=>融丰(todo)]
    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.go_pay:
                if (zfb) {// 支付宝支付
                    if (pay_code_type.equals("estore")){
                        userPresenter.payHouse(uid, pay_code_type, items, "6325", "0",
                                Double.parseDouble(money)*100+"", "0");
                    }else {
                        userPresenter.payHouse(uid, pay_code_type, items, "6325", "0",
                                "", "0");
                    }
                } else if (yue) {// 余额支付
                    passPopupWindow = new WritePassPopupWindow(this, this);
                    pass = (EditText) passPopupWindow.getContentView()
                            .findViewById(R.id.pass);
                    passPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                    passPopupWindow.setFocusable(true);
                    passPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
                    passPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    passPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                } else if (yhk) {// 融丰支付
                    if (bankId == null) {
                        ByAlert.alert("请先选择要支付的银行卡");
                        return;
                    }
                    if (pay_code_type.equals("estore")){
                        userPresenter.payHouse(uid, pay_code_type, items, "6327", "",
                                Double.parseDouble(money)*100+"", "0");
                    }else {
                        userPresenter.payHouse(uid, pay_code_type, items, "6327", "",
                                "", "0");
                    }

                    // userPresenter.yinhangkaPay();
                } else if (xiaotong) {
                    if (pay_code_type.equals("estore")){
                        userPresenter.payHouse(uid, pay_code_type, items, "6428", "",
                                Double.parseDouble(money)*100+"", "0");
                    }else {
                        userPresenter.payHouse(uid, pay_code_type, items, "6428", "",
                                "", "0");
                    }

                }else if (safety){
                    if (bankId == null) {
                        ByAlert.alert("请先选择要支付的银行卡");
                        return;
                    }
                    if (pay_code_type.equals("estore")){
                        userPresenter.payHouse(uid, pay_code_type, items, "6693", "",
                                Double.parseDouble(money)*100+"", "0");
                    }else {
                        userPresenter.payHouse(uid, pay_code_type, items, "6693", "",
                                "", "0");
                    }

                }
                break;
            case R.id.close_icon:
                finish();
                break;
            case R.id.zhifubao_selectBtn:
                zfb = true;
                wx = false;
                yue = false;
                yhk = false;
                xiaotong = false;
                safety=false;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.select);
                wx_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.safety_selectBtn:
                zfb = false;
                wx = false;
                yue = false;
                yhk = false;
                xiaotong = false;
                safety=true;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.VISIBLE);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                wx_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                safety_selectBtn.setBackgroundResource(R.drawable.select);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.wx_selectBtn:
                zfb = false;
                wx = true;
                yue = false;
                yhk = false;
                xiaotong = false;
                safety=false;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                wx_selectBtn.setBackgroundResource(R.drawable.select);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");

                break;
            case R.id.xiaotong_selectBtn:
                setXiaoTong();
                break;
            case R.id.yue_selectBtn:
                wx = false;
                zfb = false;
                yhk = false;
                yue = true;
                xiaotong = false;
                safety=false;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                wx_selectBtn.setBackgroundResource(R.drawable.unselect);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.select);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.yinhangka_selectBtn:
                wx = false;
                zfb = false;
                yhk = true;
                yue = false;
                xiaotong = false;
                safety=false;
                choose_card.setVisibility(View.VISIBLE);
                choose_safetycard.setVisibility(View.GONE);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.select);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                wx_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.choose_card:// 选择银行卡
                Intent intent = new Intent(this, ActivityZhangHu.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 101);
                break;
            case R.id.choose_safetycard:// 添加平安银行卡
                Intent intent1 = new Intent(this, ActivityZhangHu.class);
                intent1.putExtra("type", 5);
                startActivityForResult(intent1, 103);
                break;
            case R.id.btn_ok:
                String password = pass.getText().toString();
                if (password.equals("")) {
                    ByAlert.alert("请输入余额支付密码");
                    return;
                }
                userPresenter.yueYanzheng(uid, password);
                passPopupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                passPopupWindow.dismiss();
                break;
            default:
                break;
        }
    }

    int position = -1;
    CharSequence[] xiaoTongItems = {"3", "6", "12"};

    private void setXiaoTong() {
        position = -1;
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择分期数");
        alert.setSingleChoiceItems(xiaoTongItems, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                position = which;
            }
        });
        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (position == -1) {
                    position = 0;
                }
                fenQiCount = xiaoTongItems[position];
                zfb = false;
                wx = false;
                yue = false;
                yhk = false;
                xiaotong = true;
                safety=false;
                wx_selectBtn.setBackgroundResource(R.drawable.unselect);
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.select);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                txt_xiaotong.setText("小通分期("+xiaoTongItems[position]+"期)");
            }
        });
        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alert.create();
        alert.show();

    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_pay_type;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        if (arg0 == 101 && arg1 == 102) {
            BindCardsList bindCardsList = (BindCardsList) arg2
                    .getSerializableExtra("model");
            bankId = bindCardsList.getId();
            bank_type.setText(bindCardsList.getBank().get(0));
            card_type.setText(bindCardsList.getBank().get(1));

            String num = bindCardsList.getBankNo();//银行卡号
            if (num.length() > 4) {
                String s = num.substring(num.length() - 4, num.length());//后四位
                String ss = num.substring(0, num.length() - 4);//后四位
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < ss.length(); i++) {
                    sb.append("*");
                }
                item_zhanghu_num.setText(sb + s);
            } else {
                item_zhanghu_num.setText(bindCardsList.getBankNo());
            }
        }else if (arg0 == 103 && arg1 == 102){
            BindCardsList bindCardsList = (BindCardsList) arg2
                    .getSerializableExtra("model");
            bankId = bindCardsList.getId();
            bank_safetytype.setText(bindCardsList.getBank().get(0));
            card_safetytype.setText(bindCardsList.getBank().get(1));

            String num = bindCardsList.getBankNo();//银行卡号
            if (num.length() > 4) {
                String s = num.substring(num.length() - 4, num.length());//后四位
                String ss = num.substring(0, num.length() - 4);//后四位
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < ss.length(); i++) {
                    sb.append("*");
                }
                item_zhanghu_safetynum.setText(sb + s);
            } else {
                item_zhanghu_safetynum.setText(bindCardsList.getBankNo());
            }
        }
    }



    //string 转long
    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Long stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = formatter.parse(strTime);
        return date.getTime();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onInit()  {
        // TODO Auto-generated method stub
        setStatusBarHeight(v_statusbar);
        dialog = new WriteYanZhengMaDialog(this);
        add_shap_title_tv.setText("立即支付");
        money = getIntent().getStringExtra("money");
        contracNo = getIntent().getStringExtra("contracNo");
        items = getIntent().getStringExtra("itemid");
        pay_code_type = getIntent().getStringExtra("pay_code_type");
        creatTime=getIntent().getLongExtra("time",0);

        try {
            Long aLong1 = stringToDate("2018-07-24 00:00:00", "yyyy-MM-dd HH:mm:ss");
            if (creatTime>=aLong1){
                    seventh.setVisibility(View.GONE);
                    inner.setVisibility(View.GONE);
                    re_xiaotong.setVisibility(View.GONE);
                }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        heji.setText("总金：" + money);
        if (pay_code_type != null) {
            if (pay_code_type.equals("qianmi")||pay_code_type.equals("estore")) {
                benqi.setText("充值金额：" + money);
            } else {
                benqi.setText("本期金额：" + money);
            }
        }
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        userPresenter = new UserPresenter(this);
        zhifubao_selectBtn.setBackgroundResource(R.drawable.select);
        wx_selectBtn.setBackgroundResource(R.drawable.unselect);
        yue_selectBtn.setBackgroundResource(R.drawable.unselect);
        yinhangka_selectBtn.setBackgroundResource(R.drawable.unselect);
        xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
        safety_selectBtn.setBackgroundResource(R.drawable.unselect);
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    WriteYanZhengMaDialog dialog;

    @SuppressLint("NewApi")
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.payHouse_success) {
                payInfo = (PayInfo) entity.getData();
                if (zfb) {
                    payInfo = (PayInfo) entity.getData();
                    zfb(payInfo);
                } else if (yue) {
                    if (payInfo.getPaySuccess().equals("1")) {
                        ByAlert.alert("已经通过余额支付成功");
                        OrderDetailActivity.getContext().finish();
                        finish();
                    }
                } else if (yhk) {
                    dialog.show(getFragmentManager(), "");
                    dialog.setCancelable(false);
                    userPresenter.rfPay(uid, payInfo.getCode(), bankId);// 融丰支付
                } else if (xiaotong) {
                    Intent intent = new Intent(this, WebActivity.class);
                    ///ulinkpay/pay/pay_code/(支付号)/pay_nper/(分期期数)
                    intent.putExtra("url", NetPublicConstant.URL + "/ulinkpay/pay/pay_code/" + payInfo.getCode() + "/pay_nper/" + fenQiCount.toString());
                    startActivity(intent);
//                    finish();
                }else if (safety){
                    userPresenter.safety(uid, payInfo.getCode(), bankId);// 平安支付
                }
            } else if (entity.getEventType() == UserPresenter.payHouse_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.rfpayyuzhifu_success) {
                RongFengsBean bean = (RongFengsBean) entity.getData();
                orderCode = bean.getOrder_no();
            } else if (entity.getEventType() == UserPresenter.rfpayyuzhifu_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.yzyue_success) {
                userPresenter.payHouse(uid, pay_code_type, items, "6325", Double.parseDouble(money) * 100 + "",
                        "", "1");
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.yzyue_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.yzrf_success) {
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == UserPresenter.yzrf_fail) {
                ByAlert.alert(entity.getData());
            }else if (entity.getEventType() == UserPresenter.safetyPay_success){
                ByAlert.alert(entity.getMsg());
                finish();
            }else if (entity.getEventType() == UserPresenter.safetyPay_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
    }

    private static final int SDK_PAY_FLAG = 1;

    /**
     * 支付宝
     */
    private void zfb(PayInfo bean) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        Log.d("======PayInfo====",bean.toString());
        String money = bean.getTotalPrice();
        double m = Double.parseDouble(money) / 100;
        String content = bean.getName();
        String code = bean.getCode();
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(SPContants.APPID, m + "", content, code, TimeFormat.getSimData());
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, SPContants.RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };
    private String yu_e;
    private String code;
    private Object orderCode;


    @SuppressLint("NewApi")
    @Override
    public void getEditText(String edit) {
        // TODO Auto-generated method stub
        code = edit;
        userPresenter.sendRf(orderCode, code);
        dialog.dismiss();
    }

    @SuppressLint("NewApi")
    @Override
    public void cancel() {
        // TODO Auto-generated method stub
        dialog.dismiss();
    }


}
